<?php

class Object extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		
		$this->load->library('form_validation');
		//$this->load->library('FineUploader');
		$this->load->model('user_mgmt');
		// autoload.php
		// library: Thank_auth, database
		// helper: url
	}

	public function index()
	{
		
	}
	
	public function get_things($param = null)
	{
		if(is_numeric($param))
		{
			// get one item
			$query = $this->db->select('uid, id, title, description, price, lat, lng, username, added, modified, imgURL')->get_where('objectsusers', array('id' => $param));
		}
		if($param == 'm')
		{
			// get user item(s)
			$query = $this->db->select('uid, id, title, description, price, lat, lng, username, added, modified, imgURL')->get_where('objectsusers', array('uid' => $this->tank_auth->get_user_id()));
		}
		else
		{
			// get all items
			$query = $this->db->select('uid, id, title, description, price, lat, lng, username, added, modified, imgURL')->get('objectsusers');
		}
		
		/* create one master array of the records */
	 	$results = array();
	 	foreach ($query->result_array() as $row)
		{
			$row['added'] = $this->unix2human(time() - strtotime($row['added']));
			//date("D, d M y H:i:s O",strtotime($row['added']));
			$results[] = $row;
		}
		
		//print_r($results);

		header('Content-type: application/json');
		echo json_encode($results);
	}
	
	
	/*
	 *  Get items when geographical bounds are available
	 */
	public function get_bounds()
	{
		// check the value of param
		// to be coded!
		
		// get bounds
		$bounds = $_POST['data'];
		
			$this->db->select('uid, id, title, description, price, lat, lng, username, added, modified, imgURL');
			$this->db->where('lat <',round($bounds[0],4));
			$this->db->where('lat >',round($bounds[2],4));
			$this->db->where('lng >',round($bounds[1],4));
			$this->db->where('lng <',round($bounds[3],4));
			$query = $this->db->get('objectsusers');
	
		/* create one master array of the records */
		$results = array();
		foreach ($query->result_array() as $row)
		{
			$row['added'] = $this->unix2human(time() - strtotime($row['added']));
			//date("D, d M y H:i:s O",strtotime($row['added']));
			$results[] = $row;
		}
	
		//print_r($results);
	
		header('Content-type: application/json');
		echo json_encode($results);
	}
	
	public function create()
	{
		//if($this->tank_auth->is_logged_in()) {
			//$this -> form_validation -> set_error_delimiters('<span class="error">', '</span>');
			
			// rules
			$this->form_validation->set_rules('title', 'Title', 'trim|required|xss_clean');
			$this->form_validation->set_rules('description', 'Description', 'trim|xss_clean');
			$this->form_validation->set_rules('price', 'Price', 'required|numeric');
			$this->form_validation->set_rules('lat', 'lat', 'required|numeric');
			$this->form_validation->set_rules('lng', 'lng', 'required|numeric');
			$this->form_validation->set_rules('terms', 'Terms', 'trim|required|xss_clean');
			$this->form_validation->set_rules('imgURL', 'imgURL', 'trim|xss_clean');
			
			if($this->form_validation->run() == FALSE)
			{
				echo 'fail_form';
			}
			else
			{
				date_default_timezone_set('UTC');
				$date = date('Y-m-d H-i-s');
				if($_POST['imgURL'] != NULL)
				{
					$imgURL = $_POST['imgURL'];
				}
				else
				{
					// no picture uploaded
					$imgURL = 'empty';
				}
					
				$data = array(
					'uid'		  => $_POST['uid'],
				//'uid'	 	  => $this->tank_auth->get_user_id(),
					'title' 	  => $_POST['title'],
					'description' => $_POST['description'],
					'price'		  => $_POST['price'],
					'lat' 		  => $_POST['lat'],
					'lng'		  => $_POST['lng'],
					'added'       => $date,
					'imgURL'      => $imgURL
				);
				
				$this->db->insert('objects', $data);
				echo "success";
			}
		/*}
		else
		{
			echo 'fail_login';
		}*/
	}
	
	public function delete($id)
	{
		if($this->tank_auth->is_logged_in()) {
			if(isset($id))
			{
				$this->db->where('id', $id)->delete('objects');
				echo 'success';
			}
			else
			{
				echo 'fail';
			}
		}
		else
		{
			echo 'fail_loggin';
		}
		
	}
	
	public function update()
	{
	
		//if($this->tank_auth->is_logged_in()) 
		{
			$this -> form_validation -> set_error_delimiters('<span class="error">', '</span>');
			
			// rules
			$this->form_validation->set_rules('title', 'Title', 'trim|required|xss_clean');
			$this->form_validation->set_rules('price', 'Price', 'required|numeric');
			$this->form_validation->set_rules('description', 'Description', 'trim|required|xss_clean');
			$this->form_validation->set_rules('lat', 'lat', 'required');
			$this->form_validation->set_rules('lng', 'lng', 'required');
			
			if($this->form_validation->run() == FALSE)
			{			
			
				echo 'fail_form';
			
			}
			else
			{
				$data = array(
					'id' => $_POST['id'],
					'title' => $_POST['title'],
					'price' => $_POST['price'],
					'description' => $_POST['description'],
					'lat' => $_POST['lat'],
					'lng' => $_POST['lng']
				);
				$id=$_POST['id'];
				//echo $_POST['description'];
				
				$this->db->where('id', $id);
				$this->db->update('objects',$data);
				echo "success";
			}	
		}
		/*else
		{
			echo 'fail';
		}*/
	}
	
	
	public function search()
	{
		$this->form_validation->set_rules('string', 'search word', 'trim|required|xss_clean');
		
		if($this->form_validation->run() == FALSE)
		{
			echo 'fail_form';
		}
		else
		{
			$string = $_POST['string'];
			
			$results = array();
			if($_POST['param'] == 'm' && $this->tank_auth->is_logged_in()) // search only in the user things
			{
				//echo 'logged';
				$query = $this->db->query('SELECT * FROM adon_objects WHERE MATCH ( title, description ) AGAINST ("'.$string.'*" IN BOOLEAN MODE)');
				foreach ($query->result_array() as $row)
				{
					//echo 'halo';
					//echo print_r($row);
					if($row['uid'] == $this->tank_auth->get_user_id())
					{
						$results[] = $row;
					}
					//echo print_r($results);
				}
			}
			else
			{
				$query = $this->db->query('SELECT * FROM adon_objects WHERE MATCH ( title, description ) AGAINST ("'.$string.'*" IN BOOLEAN MODE)');
				foreach ($query->result_array() as $row)
				{
					$results[] = $row;
				}
			}
			
			foreach($results as $i=>$value)
			{
				$results[$i]['title'] = $this->highlightWords($results[$i]['title'],$string);
				$results[$i]['description'] = $this->truncateText($results[$i]['description'],50);
				$results[$i]['description'] = $this->highlightWords($results[$i]['description'],$string);
			}
			
			header('Content-type: application/json');
			if(!empty($results))
			{
				echo json_encode($results);
			}
		}
	}
	
	// highlight a word
	private function highlightWords($string,$words){
		
		$words=explode(' ',$words);
		
		for($i=0;$i<sizeOf($words);$i++) {
			 $string=str_ireplace($words[$i], '<strong class="highlight">'.$words[$i].'</strong>', $string);
		}
		
		return $string;
	}
	
	private function truncateText($text,$max_characters)
	{
		// Test si la longueur du texte dépasse la limite
		if (strlen($text)>$max_characters)
		{
		  // Séléction du maximum de caractères
		  $text = substr($text, 0, $max_characters);
		  // Récupération de la position du dernier espace (afin déviter de tronquer un mot)
		  $space_position = strrpos($text, " ");
		  $text = substr($text, 0, $space_position);
		  // Ajout des "..."
		  $text = $text."...";
		} 
		return $text;
	}
	
	/**
	 2058	 * Determines the difference between two timestamps.
	 2059	 *
	 2060	 * The difference is returned in a human readable format such as "1 hour",
	 2061	 * "5 mins", "2 days".
	 2062	 *
	 2063	 * @since 1.5.0
	 2064	 *
	 2065	 * @param int $from Unix timestamp from which the difference begins.
	 2066	 * @param int $to Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
	 2067	 * @return string Human readable time difference.
	 2068	 */
	
	private function unix2human($unix) {

    //--------------------------------------------------
    // Maths

        $sec = $unix % 60;
        $unix -= $sec;

        $minSeconds = $unix % 3600;
        $unix -= $minSeconds;
        $min = ($minSeconds / 60);

        $hourSeconds = $unix % 86400;
        $unix -= $hourSeconds;
        $hour = ($hourSeconds / 3600);

        $daySeconds = $unix % 604800;
        $unix -= $daySeconds;
        $day = ($daySeconds / 86400);

        $week = ($unix / 604800);

    //--------------------------------------------------
    // Text

        $output = '';

        if ($week > 0) $output .= ', ' . $week . ' week'   . ($week != 1 ? 's' : '');
        if ($day  > 0) $output .= ', ' . $day  . ' day'    . ($day  != 1 ? 's' : '');
        if ($hour > 0) $output .= ', ' . $hour . ' hour'   . ($hour != 1 ? 's' : '');
        if ($min  > 0) $output .= ', ' . $min  . ' minute' . ($min  != 1 ? 's' : '');

        if ($sec > 0 || $output == '') {
            $output .= ', ' . $sec  . ' second' . ($sec != 1 ? 's' : '');
        }

    //--------------------------------------------------
    // Grammar

        $output = substr($output, 2);
        $output = preg_replace('/, ([^,]+)$/', ' and $1', $output);

    //--------------------------------------------------
    // Return the output

        return $output;

	}
/*
	public function upload()
	{
		//Example of how to use this uploader class...
		//You can uncomment the following lines (minus the require) to use these as your defaults.
		
		// list of valid extensions, ex. array("jpeg", "xml", "bmp")
		$allowedExtensions = array('jpeg', 'jpg');
		// max file size in bytes
		// 200 * 1024 = 200kB
		$sizeLimit = 200 * 1024;
		
		$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
		
		// Call handleUpload() with the name of the folder, relative to PHP's getcwd()
		$result = $uploader->handleUpload('./assets/img/');
		
		// to pass data through iframe you will need to encode all html tags
		echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
		
	}
*/	
	
}

